/**
 * 测试类的接口
 * Created by dongchen on 16/5/11.
 */
var express = require('express');
var router = express.Router();

var co = require('co');
var coRequest = require('co-request');
var dao = require('../dao');
var moment = require('moment');

var _ = require('lodash');
var utils = require('utility');
var LicenseCenter = require('../lib/LicenseCenter');
var commonUtils = require('../lib/commonUtils');

/**
 * 获取微信服务调用的access_token
 * 先读取本地文件缓存, 如果没有access_token或临近过期,则请求微信服务器获取新token
 */
router.get('/api/token', function (req, res) {

    co(function*(){
        var result = yield LicenseCenter.access_token(req.query.refresh);
        res.json(result);
    }).catch(function (err) {
        console.error(err.stack);
    });
});

router.get('/api/ticket', function (req, res) {

    co(function*(){
        var result = yield LicenseCenter.jsapi_ticket(req.query.refresh);
        res.json(result);
    }).catch(function (err) {
        console.error(err.stack);
    });
});

router.get('/api/getPackage', function(req, res){
    var url = 'http://117.34.66.244:8080/api.aspx';
    var apiKey = '59626a56b3c24a2f9af0da7f66634365';
    var account = 'woyunxx';

    var body = {
        account : account,
        type : 0
    };

    body.sign = getSign(body, apiKey);
    body.action = 'getPackage';
    body.v = '1.1';

    url = commonUtils.buildUrl(url, body);
    console.log(url);
    co(function*(){
        var result = yield coRequest.get(url);
        res.json(JSON.parse(result.body));
    }).catch(function (err) {
        console.error(err.stack);
    });
});

router.get('/api/charge', function(req, res){
    var url = 'http://117.34.66.244:8080/api.aspx';
    var apiKey = '59626a56b3c24a2f9af0da7f66634365';
    var account = 'woyunxx';

    var body = {
        account : account,
        mobile : '15802986461',
        'package' : '10'
    };

    body.sign = getSign(body, apiKey);
    body.action = 'charge';
    body.v = '1.1';
    body.range = '0';
    body.outtradeno = '1234567890';

    url = commonUtils.buildUrl(url, body);
    console.log(url);
    co(function*(){
        var result = yield coRequest.get(url);
        res.json(JSON.parse(result.body));
    }).catch(function (err) {
        console.error(err.stack);
    });
});

router.get('/push/message', function(req, res){
    function * handler(){


        var result = yield LicenseCenter.access_token();
        var url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${result}`;
        yield coRequest.post({
            url : url,
            json : true,
            body : {
                touser : 'oFs7Ovx2W2X9oEKWmXyzcQhSh7_0',
                template_id : 'vEiYHqFgPQESi6biu6SvwH5e3xc2qBbNLI6Z34QOrBg',
                // url : 'http://weixin.qq.com/download',
                data :{
                    first : {
                        value : '亲,您的流量已充值成功\n'
                    },
                    keyword1 : {
                        value : '13401175123',
                        color : '#173177'
                    },
                    keyword2 : {
                        value : '200G',
                        color : '#173177'
                    },
                    keyword3 : {
                        value : '2016-06-09 22:22:22'
                    },
                    remark : {
                        value : '\n感谢您的使用'
                    }
                }
            }
        });
    }
    commonUtils.coHandler(handler, res);
});

router.get('/push/message/2', function(req, res){
    function * handler(){

        var order = yield dao.Order.findOne({order_id : '160520155845oFs70001'});
        if(!order){
            return;
        }
        var user = yield dao.User.findOne({id : order.payer_id});
        console.log(`user = ${user}`);
        if(!user){
            return;
        }

        var token = yield LicenseCenter.access_token();
        var url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${token}`;
        var tplId = 'vEiYHqFgPQESi6biu6SvwH5e3xc2qBbNLI6Z34QOrBg';


            var response = yield coRequest.post({
                url : url,
                json : true,
                body : {
                    touser : user.open_id,
                    template_id : tplId,
                    // url : 'http://weixin.qq.com/download',
                    data :{
                        first : {
                            value : '亲,您的流量已充值成功\n'
                        },
                        keyword1 : {
                            value : order.mobile,
                            color : '#173177'
                        },
                        keyword2 : {
                            value : order.package,
                            color : '#173177'
                        },
                        keyword3 : {
                            value : moment(order.update_time).format('YYYY-MM-DD hh:mm:ss')
                        },
                        remark : {
                            value : '\n感谢您的使用'
                        }
                    }
                }
            });
            console.log(response.body);
    }
    commonUtils.coHandler(handler, res);
});

function getSign(body, secret, algorithm){
    var keyArr = _.keys(body).sort();
    var tmp = [];
    _.each(keyArr, function(key){
        if(body[key] !== undefined){
            var lowKey = key.toLowerCase();
            var value = body[key];
            tmp.push(`${lowKey}=${value}`);
        }
    });
    tmp.push('key=' + secret);

    var signStr = tmp.join('&');
    console.log(signStr);
    if(algorithm){
        return utils[algorithm](signStr);
    }else{
        return utils.md5(signStr).toLowerCase();
    }

}

module.exports = router;